#include "SubsystemBodiesBase.h"
#include "Components/ComponentPlayer.h"
#include "Components/ComponentBody.h"
#include "Terrain/Terrain.h"
#include "Managers/BlocksManager.h"
#include "Subsystems/SubsystemTimeOfDay.h"

#include "Player/PlayerData.h"
#include "GameSingleton.h"
#include "GameRegistry.hpp"
#include "Network/Packages/SubsystemBodyPackage.h"

#include "Log.h"

namespace PocketSurvival
{
    void SubsystemBodiesBase::update(float dt)
    {
        if (m_timeOfDay->periodicGameTimeEvent(1.0, 0.0))
        {
            m_bodiesMutex.lock();

            m_componentBodiesByArea.clear();
            // m_bodyKeyMap.clear(); // 这个就不用清理了，updateBody会修改body所出在哪个区域
            for(auto it = m_bodyKeyMap.begin(); it != m_bodyKeyMap.end(); ++it)
            {
                updateBody(it->first);
            }

            m_bodiesMutex.unlock();
        }

        // 发送动物位置给客户端
        if (m_timeOfDay->periodicGameTimeEvent(0.1, 0.0))
        {
            auto view = GameSingleton::gameRegistry->view<ComponentBody*>();
            std::vector<ComponentBody*> comBodyVec;
            for (entt::entity entity : view)
            {
                ComponentBody *body = view.get<ComponentBody*>(entity);
                if (body->componentPlayer == nullptr)
                {
                    comBodyVec.push_back(body);
                }
            }
            std::shared_ptr<SubsystemBodyPackage> package = std::make_shared<SubsystemBodyPackage>(comBodyVec);
            package->sendType = PackageSendType::ALL;
            GameSingleton::packageManager->addSendPackageToQueue(package);

            // std::unordered_set<ComponentBody*> comBodySet;

            // auto view = GameSingleton::gameRegistry->view<ComponentPlayer*>();
            // for(entt::entity entity : view)
            // {
            //     ComponentPlayer* player = view.get<ComponentPlayer*>(entity);
            //     comBodySet.clear();

            //     Vector3 position;
            //     player->componentBody->getPosition(position);

            //     findBodiesAroundPoint(Vector2(position.posX, position.posZ), 64.0f, comBodySet);
            //     // 若Body是玩家自己的话，是不用发送的
            //     auto it = comBodySet.find(player->componentBody);
            //     if(it != comBodySet.end())
            //     {
            //         comBodySet.erase(it);
            //     }

            //     Log::Info(fmt::format("send body: {}, count: {}", player->playerData->username, comBodySet.size()));

            //     std::shared_ptr<SubsystemBodyPackage> package = std::make_shared<SubsystemBodyPackage>(comBodySet);
            //     package->sendType = PackageSendType::TARGET;
            //     package->client = player->playerData->client;
            //     GameSingleton::packageManager->addSendPackageToQueue(package);
            // }
        }


    }
}